// 优化的用户登录云函数
const cloud = require('wx-server-sdk')
const request = require('request-promise')

cloud.init({
  env: 'cloud1-8g3kxnyv58f85f9b'
})

const db = cloud.database()

// 微信小程序配置
const APPID = 'wx10b43811fd078207';
const SECRET = 'a7e7893c0e2bc3185f59974337699404';

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { code, phone } = event

  try {
    // 获取openid和session_key
    let openid = wxContext.OPENID
    let session_key = ''

    if (APPID && SECRET && code) {
      const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${SECRET}&js_code=${code}&grant_type=authorization_code`;
      const result = await request({
        url: url,
        json: true
      });

      if (result.openid) {
        openid = result.openid
        session_key = result.session_key || ''
      }
    }

    // 使用事务处理用户登录
    const transaction = await db.startTransaction()

    try {
      // 第一步：将该用户之前的所有登录记录的login_status设置为0
      const updatePreviousResult = await transaction.collection('user').where({
        _openid: openid,
        login_status: 1
      }).update({
        data: {
          login_status: 0,
          logout_time: db.serverDate()
        }
      })

      console.log('将之前的登录状态设置为0，影响记录数:', updatePreviousResult.stats.updated)

      // 第二步：插入新的登录记录
      const newLoginResult = await transaction.collection('user').add({
        data: {
          phone: phone,
          openid: openid,
          session_key: session_key,
          login_status: 1,
          create_time: db.serverDate(),
          login_time: db.serverDate(),
          update_time: db.serverDate()
        }
      })

      console.log('新登录记录创建成功:', newLoginResult._id)

      // 提交事务
      await transaction.commit()

      return {
        success: true,
        openid: openid,
        session_key: session_key,
        phone: phone,
        loginRecordId: newLoginResult._id,
        previousRecordsUpdated: updatePreviousResult.stats.updated,
        message: updatePreviousResult.stats.updated > 0 ? '登录成功' : '首次登录成功'
      }

    } catch (transactionError) {
      // 回滚事务
      await transaction.rollback()
      console.error('事务处理失败:', transactionError)

      return {
        success: false,
        error: 'database_transaction_failed',
        message: '数据库操作失败',
        details: transactionError.message
      }
    }

  } catch (error) {
    console.error('登录云函数执行失败:', error)

    return {
      success: false,
      error: 'login_function_failed',
      message: '登录失败，请重试',
      details: error.message
    }
  }
}
